package com.xx.dk.tbsalling.aismessages.utils;

import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @description:
 * @author: xx
 * @Date 2023/7/24 15:14
 * @version: 1.0
 */
public class FixedSizeQueue<E> {
    private final BlockingQueue<E> queue;
    public FixedSizeQueue(int capacity) {
        queue = new ArrayBlockingQueue<>(capacity);
    }

    public void add(E e) {
        // 如果队列已满，则先移除队列头部的元素
        if (queue.remainingCapacity() == 0) {
            queue.poll();
        }
        // 添加新元素到队列尾部
        queue.add(e);
    }

    public E remove() throws InterruptedException {
        return queue.take();
    }

    public String toString() {
        Iterator<E> it = queue.iterator();
        if (! it.hasNext())
            return "[]";

        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            E e = it.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (! it.hasNext())
                return sb.append(']').toString();
            sb.append(',').append(' ');
        }
    }
}
